import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import TimeoutException
import json
from time import sleep
import os
import re



def initialize_driver(proxy=None):
	chrome_options = Options()
	chrome_options.add_argument("--disable-blink-features=AutomationControlled")
	chrome_options.add_experimental_option("useAutomationExtension", False)
	chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
	chrome_options.add_argument("--start-maximized")
	chrome_options.add_argument("--lang=zh-CN")
	chrome_options.add_argument(
		"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
	if proxy:
		chrome_options.add_argument(f'--proxy-server={proxy}')
	# 浏览器驱动器路径
	chrome_driver_path = os.path.join(os.path.dirname(__file__), "static", 'chromedriver.exe')
	print(chrome_driver_path)
	# print(chrome_driver_path)
	server1 = Service(chrome_driver_path)
	driver = webdriver.Chrome(options=chrome_options, service=server1)
	driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
		"source": """
	            Object.defineProperty(navigator, 'webdriver', {
	                get: () => undefined
	            });
	            window.navigator.chrome = {
	                runtime: {},
	            };
	            Object.defineProperty(navigator, 'languages', {
	                get: () => ['zh-CN', 'zh']
	            });
	            Object.defineProperty(navigator, 'plugins', {
	                get: () => [1, 2, 3,4,5]
	            });
	        """
	})
	# # 打印IP地址
	# ip_element = driver.find_element_by_xpath('//body')
	# print("当前IP地址:", ip_element.text)

	# 初始化浏览器
	return driver


if __name__ == "__main__":
	url = "http://api.dmdaili.com/dmgetip.asp?apikey=555ecc68&pwd=22d76b8db89e7c455a8aedc76ce26843&getnum=1&httptype=1&geshi=1&fenge=1&fengefu=&operate=all&setcity=all&provin=hebei"
	prox = requests.get(url)
	print(prox.status_code)
	print(prox.text)
	# print(prox.json())

	driver = initialize_driver(prox.text)
	sleep(100)